<template>
  <div class="coupon-page">
    <van-nav-bar title="优惠券" left-text="" left-arrow @click-left="goBack"/>
    <van-tabs v-model="currentTab" @change="changeTab">
      <van-tab title="全部" name="all"></van-tab>
      <van-tab title="已使用" name="used"></van-tab>
      <van-tab title="已过期" name="expired"></van-tab>
    </van-tabs>
    <div class="coupon-list">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="filteredCoupons.length === 0" class="no-coupons">
        暂无优惠券
      </div>
      <div v-else>
        <div class="coupon-item" v-for="(coupon, index) in filteredCoupons" :key="coupon.couponId || index">
          <div :class="['coupon', { 'expired': coupon.expired }]"
               :style="{ backgroundColor: getBackgroundColor(coupon.usageStatus) }">
            <div class="coupon-amount">{{ coupon.amountOrDiscount }}¥</div>
            <div class="coupon-condition">满{{ coupon.couponName }}</div>
            <div class="coupon-expiry">有效期至{{ coupon.validEndTime }}</div>
            <van-button
                v-if="coupon.usageStatus === '未使用'"
                size="mini"
                type="danger"
                class="coupon-use-btn"
                @click="useCoupon(coupon)"
            >使用
            </van-button>
            <div v-else-if="coupon.usageStatus === '已过期'" class="coupon-expired-label">已过期</div>
            <div v-else class="coupon-used-label">已使用</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Tab, Tabs, Button } from 'vant';
import 'vant/lib/index.css'; // 确保这个路径正确
import axios from "axios";

export default {
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Button.name]: Button,
  },
  data() {
    return {
      coupons: [],
      currentTab: 'all',
      user: null,
      loading: false,
      status: 0 // 默认状态为全部
    };
  },
  computed: {
    filteredCoupons() {
      if (this.currentTab === 'all') return this.coupons;
      return this.coupons.filter(coupon => {
        if (this.currentTab === 'used') {
          return coupon.usageStatus === '已使用';
        } else if (this.currentTab === 'expired') {
          return coupon.usageStatus === '已过期';
        }
        return false;
      });
    },
  },
  methods: {
    getBackgroundColor(usageStatus) {
      switch (usageStatus) {
        case '未使用':
          return '#4D90FE';
        case '已使用':
          return '#FF7043';
        case '已过期':
          return '#FFD600';
        default:
          return '#ccc';
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    fetchCoupons() {
      if (!this.user || !this.user.id) {
        console.error('用户信息未找到');
        this.loading = false;
        return;
      }
      this.loading = true; // 请求开始时设置为 true
      axios.post(`http://localhost:6001/api/admin/coupon/${this.user.id}/${this.status}`).then(res => {
        if (res.data && res.data.data) {
          this.coupons = res.data.data;
          console.log('创建组件时获取到的优惠券数据:', this.coupons);
        } else {
          console.error('获取优惠券数据格式不正确:', res.data);
        }
      })
          .catch(error => {
            console.error('获取优惠券失败:', error);
            this.$toast.fail('获取优惠券失败，请重试');
          })
          .finally(() => {
            this.loading = false; // 请求结束时设置为 false
          });
    },
    changeTab(name) {
      this.currentTab = name;
      switch (name) {
        case 'used':
          this.status = 2;
          break;
        case 'expired':
          this.status = 1;
          break;
        default:
          this.status = 0; // 全部
          break;
      }
      this.fetchCoupons(); // 调用 fetchCoupons 方法获取数据
    },
    getUserInfo() {
      const userInfo = sessionStorage.getItem('userDB');
      if (userInfo) {
        try {
          this.user = JSON.parse(userInfo);
          console.log('获取到的用户信息:', this.user);
        } catch (error) {
          console.error('解析用户信息失败:', error);
          this.user = null;
        }
      } else {
        console.error('用户信息未找到');
        this.user = null;
      }
    },
    useCoupon(coupon) {
      sessionStorage.setItem("coupon", JSON.stringify(coupon));
      console.log('使用优惠券:', coupon);
      this.$router.push('/yuyue');
      // 这里可以添加使用优惠券的逻辑
    },
  },
  created() {
    this.getUserInfo();
    this.fetchCoupons(); // 初始化时获取数据
  },
};
</script>

<style scoped>
.coupon-page {
  padding: 20px;
}

.coupon-list {
  margin-top: 20px;
}

.coupon-item {
  margin-bottom: 20px;
}

.coupon {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 10px;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.coupon.expired {
  opacity: 0.5;
}

.coupon-amount {
  font-size: 24px;
}

.coupon-label {
  font-size: 16px;
}

.coupon-condition {
  font-size: 14px;
}

.coupon-expiry {
  font-size: 12px;
}

.coupon-use-btn {
  position: absolute;
  right: 10px;
  bottom: 10px;
  border-radius: 20px;
}

.coupon-expired-label {
  position: absolute;
  right: 10px;
  bottom: 10px;
  color: red;
}

.coupon-used-label {
  position: absolute;
  right: 10px;
  bottom: 10px;
  color: gray;
}

.loading {
  text-align: center;
  margin-top: 20px;
  color: #999;
}

.no-coupons {
  text-align: center;
  margin-top: 20px;
  color: #999;
}
</style>
